package com.hb.trade.server.project.notice.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.center.au.dto.OrgDTO;
import com.hb.core.pojo.enums.InviteStatusEnum;
import com.hb.core.pojo.enums.ProjectTypeEnum;
import com.hb.core.pojo.project.notice.dto.NoticeBidSectionOrgDTO;
import com.hb.core.pojo.project.notice.dto.NoticeDTO;
import com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO;
import com.hb.core.pojo.project.notice.entity.Notice;
import com.hb.core.pojo.project.notice.entity.TenderInviteEnterprise;
import com.hb.core.pojo.project.notice.mapper.NoticeMapper;
import com.hb.core.pojo.project.notice.mapper.TenderInviteEnterpriseMapper;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.notice.service.TenderInviteEnterpriseService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.MsgUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 投标邀请信息 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-08-30
 */
@Service
public class TenderInviteEnterpriseServiceImpl extends ServiceImpl<TenderInviteEnterpriseMapper, TenderInviteEnterprise> implements TenderInviteEnterpriseService {

    @Resource
    private TenderInviteEnterpriseMapper tenderInviteEnterpriseMapper;

    @Resource
    private BidSectionService bidSectionService;
    @Resource
    private NoticeMapper noticeMapper;

    /**
     * 更新或者修改邀请投标企业信息
     *
     * @param noticeDTO
     * @author tian
     * @date 2022-2-19 15:38
     */
    @Override
    public void updateInviteEnterprise(NoticeDTO noticeDTO) {
        // 获取每个标段下的投标人信息
        List<NoticeBidSectionOrgDTO> bidSectionOrgList = noticeDTO.getBidSectionOrgList();

        if (CollUtil.isNotEmpty(bidSectionOrgList)) {
            // 先判断是否已存在邀请企业信息 有就删除掉
            QueryWrapper<TenderInviteEnterprise> tenderInviteDtoQueryWrapper = new QueryWrapper<>();
            tenderInviteDtoQueryWrapper.lambda().eq(TenderInviteEnterprise::getNoticeId, noticeDTO.getId());
            remove(tenderInviteDtoQueryWrapper);

            for (NoticeBidSectionOrgDTO noticeBidSectionOrgDTO : bidSectionOrgList) {
                // 标段信息
                List<BidSectionDTO> sectionList = noticeBidSectionOrgDTO.getSectionList();
                // 标段下的投标人
                List<OrgDTO> orgList = noticeBidSectionOrgDTO.getOrgList();

                List<TenderInviteEnterprise> tenderInviteEnterpriseList = new ArrayList<>();

                // 重新添加企业信息 每个标段对应多个投标人
                TenderInviteEnterprise tenderInviteEnterprise;
                for (BidSectionDTO bid : sectionList) {
                    // 每个标段都需要添加投标人
                    for (OrgDTO org : orgList) {
                        tenderInviteEnterprise = new TenderInviteEnterprise();
                        tenderInviteEnterprise.setId(IdUtil.getId());
                        tenderInviteEnterprise.setNoticeId(noticeDTO.getId());
                        tenderInviteEnterprise.setSectionId(bid.getId());
                        tenderInviteEnterprise.setOrgId(org.getId().toString());
                        tenderInviteEnterprise.setOrgName(org.getOrgName());
                        tenderInviteEnterprise.setCreateTime(LocalDateTime.now());
                        tenderInviteEnterprise.setUpdateTime(LocalDateTime.now());
                        tenderInviteEnterpriseList.add(tenderInviteEnterprise);
                    }
                }
                saveBatch(tenderInviteEnterpriseList);
            }
        }
    }

    /**
     * 根据邀请书id和标段id查询邀请企业信息
     *
     * @param noticeId 邀请书id
     * @return java.util.List<com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO>
     * @author tian
     * @date 2022-2-19 16:17
     */
    @Override
    public List<NoticeBidSectionOrgDTO> selectTenderInviteEnterpriseByNoticeIdAndSectionId(Long noticeId) {
        // 返回的信息
        List<NoticeBidSectionOrgDTO> bidSectionOrgList = new ArrayList<>();
        // 查询邀请书都是绑定的哪些标段
        List<BidSectionDTO> bidSectionDTOS = bidSectionService.findSectionBondByNoticeId(noticeId);

        // 因为标段没涉及到分组，所以回显还是按照标段回显
        for (BidSectionDTO bidSectionDTO : bidSectionDTOS) {
            NoticeBidSectionOrgDTO noticeBidSectionOrgDTO = new NoticeBidSectionOrgDTO();

            // 返回的标段信息
            List<BidSectionDTO> sectionList = new ArrayList<>();
            sectionList.add(bidSectionDTO);
            noticeBidSectionOrgDTO.setSectionList(sectionList);

            // 返回标段下的邀请企业信息
            TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO = new TenderInviteEnterpriseDTO();
            tenderInviteEnterpriseDTO.setNoticeId(noticeId);
            tenderInviteEnterpriseDTO.setSectionId(bidSectionDTO.getId());
            List<OrgDTO> orgList = tenderInviteEnterpriseMapper.selectTenderInviteEnterpriseList(tenderInviteEnterpriseDTO);
            noticeBidSectionOrgDTO.setOrgList(orgList);

            bidSectionOrgList.add(noticeBidSectionOrgDTO);
        }
        return bidSectionOrgList;
    }


    /**
     * 投标人查询邀请书列表
     *
     * @param tenderInviteEnterpriseDTO
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO>
     * @author tian
     * @date 2022-2-19 16:35
     */
    @Override
    public Page<TenderInviteEnterpriseDTO> pageTenderInviteEnterpriseDTOByOrgId(TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO) {
        Page<TenderInviteEnterpriseDTO> pages = tenderInviteEnterpriseDTO.pages();
        baseMapper.pageTenderInviteEnterpriseDTOByOrgId(pages, tenderInviteEnterpriseDTO);
        if (!pages.getRecords().isEmpty()) {
            for (TenderInviteEnterpriseDTO inviteEnterpriseDTO : pages.getRecords()) {
                // 前端显示字段
                inviteEnterpriseDTO.setAgencyOrganizeName(inviteEnterpriseDTO.getAgencyOrganizeInfo().getName());
                inviteEnterpriseDTO.setInviteStatusName(Enums.of(InviteStatusEnum.class, inviteEnterpriseDTO.getInviteStatus()).getShowName());
                inviteEnterpriseDTO.setProjectTypeName(Enums.of(ProjectTypeEnum.class, inviteEnterpriseDTO.getProjectType()).getShowName());
            }
        }
        return pages;
    }


    /**
     * 根据id查询邀请书详情
     *
     * @param inviteEnterpriseId
     * @return com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO
     * @author tian
     * @date 2022-2-19 17:12
     */
    @Override
    public TenderInviteEnterpriseDTO findTenderInviteEnterpriseInfoById(Long inviteEnterpriseId) {
        TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO = baseMapper.findTenderInviteEnterpriseInfoById(inviteEnterpriseId);
        return tenderInviteEnterpriseDTO;
    }


    /**
     * 投标人确定回执
     *
     * @param tenderInviteEnterpriseDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.Boolean>
     * @author tian
     * @date 2022-2-21 10:00
     */
    @Override
    public Message<Boolean> confirmationReceipt(TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO) {
        // 在判断是否已经接受
        TenderInviteEnterprise inviteEnterprise = baseMapper.selectById(tenderInviteEnterpriseDTO.getId());
        if (StringUtils.isNotEmpty(inviteEnterprise.getReceiptId())) {
            return MsgUtil.fail("邀请书已被接受");
        }

        // 先判断是邀请过期
        BidSection bidSection = bidSectionService.getById(inviteEnterprise.getSectionId());
        LocalDateTime invitationEndTime = bidSection.getInvitationEndTime();
        if (invitationEndTime == null) {
            return MsgUtil.fail("操作失败, 该标段未设置邀请截止时间");
        }
        if (invitationEndTime.isBefore(LocalDateTime.now())) {
            return MsgUtil.fail("邀请时间已截止！");
        }

        TenderInviteEnterprise tenderInviteEnterprise = tenderInviteEnterpriseDTO.to(TenderInviteEnterprise.class);
        tenderInviteEnterprise.setReceiptTime(LocalDateTime.now()); // 回执时间
        Integer update = baseMapper.updateById(tenderInviteEnterprise);

        if (update == 0) {
            return MsgUtil.fail("操作失败！");
        }
        return MsgUtil.success(true);
    }


    /**
     * 获取项目下各标段的邀请书信息
     *
     * @param tenderInviteEnterpriseDTO
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO>
     * @author tian
     * @date 2022-2-21 13:06
     */
    @Override
    public Page<TenderInviteEnterpriseDTO> findInviteEnterpriseListByProjectId(TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO) {
        Page<TenderInviteEnterpriseDTO> pages = tenderInviteEnterpriseDTO.pages();
        bidSectionService.pageInvitationSectionListByProjectId(pages, tenderInviteEnterpriseDTO.getProjectId());

        for (TenderInviteEnterpriseDTO inviteEnterpriseDTO : pages.getRecords()) {
            // 查询标段绑定的 最新的已发布公告
            Notice notice = noticeMapper.getLastNoticeBySectionId(inviteEnterpriseDTO.getSectionId());
            if (notice == null) {
                inviteEnterpriseDTO.setSumCount(0);
                inviteEnterpriseDTO.setConfirmCount(0);
                inviteEnterpriseDTO.setRefuseCount(0);
                continue;
            }
            // 查询总投标人数
            List<Integer> sumList = tenderInviteEnterpriseMapper.countInviteStatusByNoticeId(notice.getId(), inviteEnterpriseDTO.getSectionId());
            // 查询确认数
            Long confirmCount = sumList.stream().filter(x -> x == 2).count();
            // 查询拒绝数
            Long refuseCount = sumList.stream().filter(x -> x == 3).count();

            inviteEnterpriseDTO.setSumCount(sumList.size());
            inviteEnterpriseDTO.setConfirmCount(confirmCount.intValue());
            inviteEnterpriseDTO.setRefuseCount(refuseCount.intValue());
        }
        return pages;
    }

    /**
     * 代理机构根据标段id查询当前标段下投标人邀请信息
     *
     * @param sectionId
     * @return com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO
     * @author tian
     * @date 2022-2-21 16:30
     */
    @Override
    public TenderInviteEnterpriseDTO findInviteEnterpriseInfoBySectionId(Long sectionId) {
        // 返回信息
        TenderInviteEnterpriseDTO inviteEnterpriseDTO = new TenderInviteEnterpriseDTO();

        BidSectionDTO bidSectionInfo = bidSectionService.findBidSectionInfoById(sectionId);
        // 查询标段绑定的 最新的已发布公告
        Notice notice = noticeMapper.getLastNoticeBySectionId(sectionId);
        // 查询总投标人数
        List<Integer> sumList = CollUtil.list(false);
        // 查询待反馈数
        int waitCount = 0;
        // 查询确认数
        int confirmCount = 0;
        // 查询拒绝数
        int refuseCount = 0;
        if (notice != null) {
            // 查询总投标人数
            sumList = tenderInviteEnterpriseMapper.countInviteStatusByNoticeId(notice.getId(), sectionId);
            // 查询待反馈数
            waitCount = CollUtil.count(sumList, (item) -> item == 1);
            // 查询确认数
            confirmCount = CollUtil.count(sumList, (item) -> item == 2);
            // 查询拒绝数
            refuseCount = CollUtil.count(sumList, (item) -> item == 3);
        }

        inviteEnterpriseDTO.setSectionCode(bidSectionInfo.getSectionCode());
        inviteEnterpriseDTO.setSectionName(bidSectionInfo.getSectionName());
        inviteEnterpriseDTO.setInvitationEndTime(bidSectionInfo.getInvitationEndTime());
        inviteEnterpriseDTO.setSumCount(sumList.size());
        inviteEnterpriseDTO.setWaitCount(waitCount);
        inviteEnterpriseDTO.setConfirmCount(confirmCount);
        inviteEnterpriseDTO.setRefuseCount(refuseCount);
        return inviteEnterpriseDTO;
    }


    /**
     * 代理机构查询标段下投标人的邀请状态
     *
     * @param tenderInviteEnterpriseDTO
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.hb.core.pojo.project.notice.dto.TenderInviteEnterpriseDTO>
     * @author tian
     * @date 2022-2-21 17:19
     */
    @Override
    public Page<TenderInviteEnterpriseDTO> findInviteEnterprisePageBySectionId(TenderInviteEnterpriseDTO tenderInviteEnterpriseDTO) {
        Page<TenderInviteEnterpriseDTO> pages = tenderInviteEnterpriseDTO.pages();

        // 查询标段绑定的 最新的已发布公告
        Notice notice = noticeMapper.getLastNoticeBySectionId(tenderInviteEnterpriseDTO.getSectionId());
        if (null != notice) {
            tenderInviteEnterpriseDTO.setNoticeId(notice.getId());
            baseMapper.pageTenderInviteEnterpriseList(pages, tenderInviteEnterpriseDTO);
            if (!pages.getRecords().isEmpty()) {
                for (TenderInviteEnterpriseDTO inviteEnterpriseDTO : pages.getRecords()) {
                    // 前端显示字段
                    inviteEnterpriseDTO.setInviteStatusName(Enums.of(InviteStatusEnum.class, inviteEnterpriseDTO.getInviteStatus()).getShowName());
                }
            }
        }
        return pages;
    }


    /**
     * 根据标段集合查询接受邀请的企业信息
     *
     * @param
     * @return org.fzzn.core.model.msg.Message
     * @author yuezheng
     * @date 2022/4/23 9:38 AM
     */
    @Override
    public List<TenderInviteEnterprise> findInviteEnterpriseByAcceptSectionList(List<Long> sectionList) {
        QueryWrapper<TenderInviteEnterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "org_id", "receipt_id").lambda().in(TenderInviteEnterprise::getSectionId, sectionList).eq(TenderInviteEnterprise::getInviteStatus, 2);
        return tenderInviteEnterpriseMapper.selectList(queryWrapper);
    }
}
